package tmproject.hlhj.fhp.anwser.customview

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.dialog_anwser.*
import tmproject.hlhj.fhp.anwser.BaseAty
import tmproject.hlhj.fhp.anwser.R
import tmproject.hlhj.fhp.anwser.activitys.AnwserHomeAty
import tmproject.hlhj.fhp.anwser.adapter.OptionAdp
import tmproject.hlhj.fhp.anwser.bean.ActiveDetailBean
import tmproject.hlhj.fhp.anwser.bean.BaseBean
import tmproject.hlhj.fhp.anwser.http.Apis
import tmproject.hlhj.fhp.anwser.http.BaseAction
import tmproject.hlhj.fhp.anwser.http.LoadingAction
import tmproject.hlhj.fhp.anwser.utils.LoadingUtils
import tmproject.hlhj.fhp.anwser.utils.LoginUtil
import tmproject.hlhj.fhp.anwser.utils.SPHelper

/**
 * Created by Never Fear   on 2018\8\20 0020.
Never More....
 */
class AnwserDilaog(private val c:Context,private val aid:Int) :Dialog(c, R.style.MyDialog), CustomTimeDown.TimeOverListener, OptionAdp.ChooseOptionListener {
    private val datas=ArrayList<String>()
    private lateinit var adp:OptionAdp
    private var nowScore=0
    private val testDatas=ArrayList<ActiveDetailBean.DataBean.QuestionsBean>()
    private var perScore:Double=0.0
    private var nowDouble=0.0
    var questionNum=0
    private var rightNum=0

    private var passScore=0
    private var giveTimes=0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_anwser)
//        this.setCancelable(false)
        adp= OptionAdp(datas)
        adp.listener=this
        recyclerview.adapter=adp
        recyclerview.layoutManager=LinearLayoutManager(c,LinearLayoutManager.VERTICAL,false)

        Apis.getActiveDetail(aid,SPHelper.getToken(c)!!)
                ?.let {
                    it
                            .subscribe(object :BaseAction<Response<ActiveDetailBean>>{
                                override fun httpSuccess(t: Response<ActiveDetailBean>) {
                                    timeCountDown.startCountDown()
                                    timeCountDown.start()
                                    timeCountDown.listener=this@AnwserDilaog
                                    testDatas.addAll(t.body().data.questions)
                                    perScore=100.0/testDatas.size
                                    passScore=t.body().data.pass_score
                                    giveTimes=t.body().data.draw_times
                                    loadQuestion()
                                }

                                override fun httpErroCode(t: BaseBean) {
                                    if (t.code==500){
                                        if (c is AnwserHomeAty){
                                            Toast.makeText(c,"登录过期了，请重新登录",Toast.LENGTH_SHORT).show()
                                            c.loginDialog?.show()
                                        }
                                        dismiss()
                                    }
                                }

                                override fun httpFail(e: Throwable?) {
                                }
                            })
                }
    }

    /*加载试题*/
    private fun loadQuestion() {
        datas.clear()
        datas.addAll(testDatas[questionNum].options)
        adp.rightOption = testDatas[questionNum].correct_option
        adp.canClick=true
        tvTittle.text="${questionNum+1}、${testDatas[questionNum].stem}"
        adp.notifyDataSetChanged()
    }
    /*下一题*/
    private fun loadNextQuestion(){
        timeCountDown.stop()
        Thread(Runnable {
            Thread.sleep(1500)
            recyclerview.post {
                questionNum++
                if (questionNum<testDatas.size){
                    timeCountDown.reStart()
                    loadQuestion()
                }else{
                    anwserOver()
                }
            }
        }).start()
    }
    /*选对*/
    override fun right() {
        rightNum++
        nowDouble+=perScore
        nowScore=nowDouble.toInt()
        setScroe()
        loadNextQuestion()
    }
    /*选错*/
    override fun wrong() {
        val itemTv = adp?.getViewByPosition(recyclerview,testDatas[questionNum].correct_option, R.id.itemTv) as TextView
        itemTv?.setBackgroundResource(R.drawable.option_item_right)
        itemTv?.setTextColor(Color.parseColor("#ffffff"))
        val itemIcon = adp?.getViewByPosition(recyclerview,testDatas[questionNum].correct_option, R.id.itemIcon) as ImageView
        itemIcon.setImageResource(R.drawable.ic_dt_zhengque)
        itemIcon.visibility=View.VISIBLE
        loadNextQuestion()
    }
    /*刷新分数*/
    fun setScroe(){
        tvScore.text="当前分数：${nowScore}"
    }
//   答题完毕
    fun anwserOver(){
        Apis.commitAnwser(aid,rightNum,SPHelper.getToken(c)!!)
                .doOnSubscribe(LoadingAction(c))
                .subscribe(object :BaseAction<Response<BaseBean>>{
                    override fun httpSuccess(t: Response<BaseBean>) {
                        if (nowScore>=passScore){
                            val bundle = Bundle()
                            bundle.putInt("type",1)
                            bundle.putInt("num",testDatas.size)
                            bundle.putInt("chance",giveTimes)
                            bundle.putInt("point",nowScore)
                            ResultDialog(c,bundle).show()
                        }else{
                            val bundle = Bundle()
                            bundle.putInt("type",2)
                            bundle.putInt("num",testDatas.size)
                            bundle.putInt("chance",giveTimes)
                            bundle.putInt("point",nowScore)
                            ResultDialog(c,bundle).show()
                        }
                    }

                    override fun httpErroCode(t: BaseBean) {
                        Toast.makeText(c,t.msg,Toast.LENGTH_SHORT).show()
                    }

                    override fun httpFail(e: Throwable?) {
                    }
                    override fun onCompleted() {
                        super.onCompleted()
                        LoadingUtils.loadingDismiss()
                        dismiss()

                    }
                })

    }
    /*倒计时结束*/
    override fun timeOver() {
        Log.e("fhp","animator为空${null==timeCountDown.animator}")
        adp.canClick=false
        if (questionNum<testDatas.size){
            wrong()
        }else{
            anwserOver()
        }
    }

    override fun dismiss() {
        if (c is AnwserHomeAty){
        }
        super.dismiss()
    }
}
